<template>
  <el-row :gutter="10" v-loading="loading">
    <el-col :xl="6" :lg="6">
      <el-card class="user" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>{{ t('account.profile.title') }}</span>
          </div>
        </template>
        <ProfileUser v-if="accountInfo" v-model="accountInfo" />
        <template #footer>
          <el-button type="primary" @click="showEditInfo"
            >{{ t('account.profile.editNickName') }}
          </el-button>
          <el-button type="primary" plain @click="showEditPwd">
            {{
              accountInfo?.accountType === 1
                ? t('profile.info.resetLocalPwd')
                : t('profile.info.resetPwd')
            }}
          </el-button>
        </template>
      </el-card>
    </el-col>
    <el-col :xl="18" :lg="18">
      <el-card class="user" shadow="hover">
        <template #header>
          <div class="card-header">
            <span>{{ t('account.profile.title2') }}</span>
          </div>
        </template>
        <template v-if="accountInfo?.accountType === 1">
          <el-tabs v-model="activeName" tab-position="top">
            <el-tab-pane :label="t('ustcstudent.view.tab.basic')" name="basic">
              <TabItemBasic
                v-if="studentInfo"
                v-model="(studentInfo as UstcStudentInfoView).basic"
              />
            </el-tab-pane>
            <el-tab-pane :label="t('ustcstudent.view.tab.university')" name="university">
              <TabItemUniversity
                v-if="studentInfo"
                v-model="(studentInfo as UstcStudentInfoView).university"
              />
            </el-tab-pane>
            <el-tab-pane :label="t('ustcstudent.view.tab.admission')" name="admission">
              <TabItemAdmission
                v-if="studentInfo"
                v-model="(studentInfo as UstcStudentInfoView).admission"
              />
            </el-tab-pane>
            <el-tab-pane :label="t('ustcstudent.view.tab.degree')" name="degree">
              <TabItemDegree
                v-if="studentInfo"
                v-model="(studentInfo as UstcStudentInfoView).degree"
              />
            </el-tab-pane>
            <el-tab-pane :label="t('ustcstudent.view.tab.personal')" name="personal">
              <TabItemPersonal
                v-if="studentInfo"
                v-model="(studentInfo as UstcStudentInfoView).personal"
              />
            </el-tab-pane>
            <el-tab-pane :label="t('ustcstudent.view.tab.work')" name="work">
              <TabItemExp v-if="studentInfo" v-model="(studentInfo as UstcStudentInfoView).work" />
            </el-tab-pane>
          </el-tabs>
        </template>
        <TabItemImr
          ref="tabItemImrRef"
          v-if="accountInfo?.accountType === 2"
          v-model="studentInfo"
          :edit="editStudent"
        />
        <template v-if="accountInfo?.accountType === 2" #footer>
          <template v-if="!editStudent">
            <el-button
              type="primary"
              @click="showEditStudentInfo"
              :disabled="pendingImrVerify?.id !== undefined"
              >{{ t('account.profile.editStudentInfo') }}
            </el-button>
            <el-popover
              v-if="pendingImrVerify?.id !== undefined"
              placement="top"
              :width="800"
              trigger="hover"
            >
              <template #reference>
                <el-button type="primary" @click="handleRevokeImrVerify"
                  >{{ t('account.profile.revokeStudentInfo') }}
                </el-button>
              </template>
              <ImrStudentInfoDiffView
                ref="diffViewRefPending"
                v-if="studentInfo && pendingImrVerifyStudentInfo"
                :student-info="pendingImrVerifyStudentInfo"
                :student-info-backup="studentInfo as ImrStudentVO"
              />
            </el-popover>
          </template>
          <template v-else>
            <el-button type="primary" @click="submitStudentInfoApply"
              >{{ t('account.profile.submitStudentInfo') }}
            </el-button>
            <el-button type="primary" plain @click="cancelStudentInfoApply"
              >{{ t('common.cancel') }}
            </el-button>
          </template>
        </template>
      </el-card>
    </el-col>
  </el-row>

  <Dialog v-model="dialogVisible" :title="t('profile.info.resetPwd')" width="600">
    <ResetPwd v-if="dialogVisible" />
  </Dialog>

  <Dialog v-model="dialogVisible2" :title="t('profile.info.resetLocalPwd')" width="500">
    <ModifyUstcLocalPwd v-if="dialogVisible2" @success="dialogVisible2 = false" />
  </Dialog>

  <Dialog :title="t('imrStudent.view.confirmTitle')" v-model="dialogVisibleConfirm" width="1200">
    <ImrStudentInfoDiffView
      ref="diffViewRef"
      v-if="studentInfo && studentInfoBackup"
      :student-info="studentInfo as ImrStudentVO"
      :student-info-backup="studentInfoBackup as ImrStudentVO"
    />
    <el-input
      class="mt-[20px]"
      v-model="modifyComment"
      maxlength="300"
      :placeholder="t('imrStudent.view.modifyPlaceholder')"
      show-word-limit
      type="textarea"
    />
    <template #footer>
      <el-button @click="submitVerify" type="primary" :disabled="verifyLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisibleConfirm = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
import _ from 'lodash-es'
import { ProfileUser, ResetPwd, ModifyUstcLocalPwd } from './components'
import TabItemImr from '@/views/core/imrstudent/TabItemImr.vue'
import TabItemBasic from '@/views/core/ustcstudent/TabItemBasic.vue'
import TabItemUniversity from '@/views/core/ustcstudent/TabItemUniversity.vue'
import TabItemAdmission from '@/views/core/ustcstudent/TabItemAdmission.vue'
import TabItemDegree from '@/views/core/ustcstudent/TabItemDegree.vue'
import TabItemPersonal from '@/views/core/ustcstudent/TabItemPersonal.vue'
import TabItemExp from '@/views/core/ustcstudent/TabItemExp.vue'
import { getInfo } from '@/api/login'
import { AccountApi, AccountVO } from '@/api/system/account'
import { UserVO, useUserStore } from '@/store/modules/user'
import ImrStudentInfoDiffView from '@/views/core/imrstudent/ImrStudentInfoDiffView.vue'
import { ImrStudentVO } from '@/api/core/imrstudent'
import { compareAndFilter } from '@/utils'
import { ImrStudentInfoVerifyApi, ImrStudentInfoVerifyVO } from '@/api/core/imrstudentinfoverify'
import { UstcStudentInfoView } from '@/types/ustcstudent'

const { t } = useI18n()

defineOptions({ name: 'Profile' })

const message = useMessage()
const userStore = useUserStore()

const dialogVisible = ref(false)
const dialogVisibleConfirm = ref(false)
const loading = ref(false)

const dialogVisible2 = ref(false)

const activeName = ref('basic')
const modifyComment = ref('')

const accountInfo = ref<AccountVO>()
const studentInfo = ref<UserVO>()
const studentInfoBackup = ref<UserVO>()

const pendingImrVerify = ref<ImrStudentInfoVerifyVO>()
const pendingImrVerifyStudentInfo = ref<ImrStudentVO>()

const getUserInfo = async () => {
  loading.value = true
  const info = await getInfo()
  accountInfo.value = info.account
  studentInfo.value = info.user
  studentInfoBackup.value = _.cloneDeep(info.user)
  if (accountInfo.value?.accountType === 2) {
    pendingImrVerify.value = await ImrStudentInfoVerifyApi.getPending()
    if (pendingImrVerify.value) {
      pendingImrVerifyStudentInfo.value = JSON.parse(pendingImrVerify.value.newValue)
    }
  }
  loading.value = false
}

const showEditInfo = async () => {
  try {
    const { value } = await ElMessageBox.prompt(
      t('account.profile.editNicknameTip'),
      t('account.profile.editNickName'),
      {
        inputValue: accountInfo.value!.nickname,
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        inputPattern: /^(?!\s*$).{2,16}$/,
        inputErrorMessage: t('account.profile.nicknameEmpty')
      }
    )
    if (value) {
      accountInfo.value!.nickname = value
      loading.value = true
      await AccountApi.updateAccountNickName(value)
      await userStore.setUserNicknameAction(value)
      message.success(t('common.updateSuccess'))
      loading.value = false
    }
  } catch {}
}

const showEditPwd = () => {
  if (accountInfo.value) {
    if (accountInfo.value.accountType === 1) {
      // 科大设置本地密码
      dialogVisible2.value = true
    } else if (accountInfo.value.accountType === 2) {
      // 联培生修改密码
      dialogVisible.value = true
    }
  }
}

const editStudent = ref(false)
const showEditStudentInfo = () => {
  editStudent.value = true
}

const tabItemImrRef = ref<InstanceType<typeof TabItemImr>>()
const submitStudentInfoApply = () => {
  if (!tabItemImrRef.value) {
    return
  }
  const isError = tabItemImrRef.value.getError()
  if (isError) {
    message.error(t('common.fillMessage'))
    return
  }
  // 对比保存逻辑
  const newValue = compareAndFilter(studentInfo.value, studentInfoBackup.value)
  // 判断变动是否为{}
  if (_.isEmpty(newValue)) {
    // 没改动 走取消逻辑
    cancelStudentInfoApply()
    return
  }

  modifyComment.value = ''
  dialogVisibleConfirm.value = true
}
const cancelStudentInfoApply = () => {
  editStudent.value = false
  // 还原可能的更改
  studentInfo.value = _.cloneDeep(studentInfoBackup.value)
}

const verifyLoading = ref(false)

const diffViewRef = ref<InstanceType<typeof ImrStudentInfoDiffView>>()
const submitVerify = async () => {
  verifyLoading.value = true
  const data: Partial<ImrStudentInfoVerifyVO> = {
    modifyFields: diffViewRef.value?.getModifyField() ?? '',
    oldValue: JSON.stringify(studentInfoBackup.value),
    newValue: JSON.stringify(studentInfo.value),
    remark: modifyComment.value
  }
  try {
    await ImrStudentInfoVerifyApi.submitModifyImrStudent(data)
    dialogVisibleConfirm.value = false
    dialogVisible.value = false
    message.success(t('common.applySuccess'))
  } finally {
    verifyLoading.value = false
    dialogVisibleConfirm.value = false
    cancelStudentInfoApply()
    await getUserInfo()
  }
}

const handleRevokeImrVerify = async () => {
  try {
    await message.confirm(t('account.profile.revokeStudentInfoTip'))
    await ImrStudentInfoVerifyApi.revokeModifyImrStudent()
    message.success(t('common.operateSuccess'))
    // 刷新列表
    await getUserInfo()
  } catch {}
}

onMounted(async () => {
  await getUserInfo()
})
</script>
<style scoped>
.user {
  //max-height: 960px;
  min-height: 500px;
  padding: 15px 20px 20px;
}

.card-header {
  display: flex;
  justify-content: center;
  align-items: center;
}

:deep(.el-card .el-card__header, .el-card .el-card__body) {
  padding: 15px !important;
}

.profile-tabs > .el-tabs__content {
  padding: 32px;
  font-weight: 600;
  color: #6b778c;
}

.el-tabs--left .el-tabs__content {
  height: 100%;
}
</style>
